package com.apexcode.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.apexcode.api.RemoteJudgeService;
import com.apexcode.api.domain.UserExeResult;
import com.apexcode.api.domain.dto.JudgeSubmitDTO;
import com.apexcode.api.domain.vo.UserQuestionResultVO;
import com.apexcode.common.core.constants.Constants;
import com.apexcode.common.core.domain.R;
import com.apexcode.common.core.enums.ProgramType;
import com.apexcode.common.core.enums.QuestionResType;
import com.apexcode.common.core.enums.ResultCode;
import com.apexcode.common.core.utils.ThreadLocalUtil;
import com.apexcode.common.security.exception.ServiceException;
import com.apexcode.friend.domain.question.Question;
import com.apexcode.friend.domain.question.QuestionCase;
import com.apexcode.friend.domain.question.es.QuestionES;
import com.apexcode.friend.domain.user.UserSubmit;
import com.apexcode.friend.domain.user.dto.UserSubmitDTO;
import com.apexcode.friend.elasticsearch.QuestionESRepository;
import com.apexcode.friend.mapper.question.QuestionMapper;
import com.apexcode.friend.mapper.user.UserSubmitMapper;
import com.apexcode.friend.rabbitmq.JudgeProducer;
import com.apexcode.friend.service.user.IUserQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName UserQuestionServiceImpl
 * @Description
 * @Author ZJX
 * @Date 2025/3/28 12:47
 * @Version 1.0
 **/
@Service
public class UserQuestionServiceImpl implements IUserQuestionService {
    @Autowired
    private QuestionESRepository questionESRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private RemoteJudgeService remoteJudgeService;

    @Autowired
    private JudgeProducer judgeProducer;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO submitDTO) {
//        根据语言类型 执行对应方法
        Integer programType = submitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)){
            // 按照java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO = buildJudgeSubmitDTO(submitDTO);
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO submitDTO) {
        Integer programType = submitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            //按照java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO = buildJudgeSubmitDTO(submitDTO);
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(userId, examId, questionId, currentTime);
        UserQuestionResultVO resultVO = new UserQuestionResultVO();
        if (userSubmit != null) {
            resultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        }else {
            resultVO.setPass(userSubmit.getPass());
            resultVO.setExeMessage(userSubmit.getExeMessage());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())) {
                resultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return resultVO;
    }

    /**
     * 构建用于评判的提交DTO对象
     * 根据用户提交的信息，从ES或数据库查询题目详情，组装评判所需的完整数据
     *
     * @param submitDTO 用户提交的DTO，包含题目ID、考试ID、用户代码等
     * @return JudgeSubmitDTO 评判所需的完整DTO，包含题目信息、测试用例等
     */
    private JudgeSubmitDTO buildJudgeSubmitDTO(UserSubmitDTO submitDTO) {
        // 获取题目ID，用于后续查询
        Long questionId = submitDTO.getQuestionId();

        // 优先从Elasticsearch查询题目信息，快速获取缓存数据
        QuestionES questionES = questionESRepository.findById(questionId).orElse(null);

        // 初始化评判DTO对象，准备填充数据
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();

        // 根据ES查询结果，决定数据来源
        if (questionES != null) {
            // ES命中：直接拷贝题目信息到评判DTO
            BeanUtil.copyProperties(questionES, judgeSubmitDTO);
        } else {
            // ES未命中：从数据库查询题目信息
            Question question = questionMapper.selectById(questionId);
            // 将数据库查询结果拷贝到评判DTO
            BeanUtil.copyProperties(question, judgeSubmitDTO);
            // 将数据库数据转换为ES对象，用于缓存
            questionES = BeanUtil.copyProperties(question, QuestionES.class);
            // 同步到ES，更新缓存以供后续使用
            questionESRepository.save(questionES);
        }

        // 设置用户ID，从线程局部变量获取当前登录用户
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID, Long.class));

        // 设置考试ID，从用户提交中获取
        judgeSubmitDTO.setExamId(submitDTO.getExamId());

        // 设置编程语言类型，从用户提交中获取
        judgeSubmitDTO.setProgramType(submitDTO.getProgramType());

        // 拼接用户代码和题目主函数，形成完整可执行代码
        judgeSubmitDTO.setUserCode(codeConnect(submitDTO.getUserCode(), questionES.getMainFuc()));

        // 解析题目测试用例，从JSON字符串转为对象列表
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);

        // 提取输入用例列表，用于评判输入
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);

        // 提取期望输出列表，用于评判对比
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outputList);

        // 返回组装好的评判DTO
        return judgeSubmitDTO;
    }

    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }
}
